﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BISPOS.Repository;
using BISPOS.Report;
using System.Deployment;
using System.Reflection;

namespace BISPOS
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        ProductRepository productRepository = new ProductRepository();
        EmployeeRepository employeeRepository = new EmployeeRepository();
        CustomerRepository customerRepository = new CustomerRepository();
        BillRepository billRepository = new BillRepository();
        BISPOSDataClassesDataContext db = new BISPOSDataClassesDataContext();
        Version version = new Version();

        public MainForm()
        {
            InitializeComponent();

            Version version = Assembly.GetExecutingAssembly().GetName().Version;
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                version = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
            this.Text = String.Format("{0} Version: {1}.{2}.{3} R{4}", this.Text, version.Major, version.Minor, version.Build, version.Revision);
        }

        private void fixDataNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
           /*BISPOSDataClassesDataContext db = new BISPOSDataClassesDataContext();
            OldBISPOSDataClassesDataContext oldDb = new OldBISPOSDataClassesDataContext();
            int count = 0;
            foreach (var oldSupplier in oldDb.APs.OrderBy(x=>x.APNAME))
            {
                db.Suppliers.InsertOnSubmit(new Supplier
                {
                    Name = oldSupplier.APNAME,
                    Address = String.Format("{0} {1}", oldSupplier.APADD1, oldSupplier.APADD2),
                    Telephone = oldSupplier.TEL,
                    Fax = oldSupplier.FAX
                });
                db.SubmitChanges();
            }


            foreach (var oldGroup in oldDb.GROUPs.OrderBy(x=>x.CODE))
            {
                db.ProductGroups.InsertOnSubmit(new ProductGroup
                {
                    Code = oldGroup.CODE,
                    Name = oldGroup.DESC
                });
                db.SubmitChanges();
            }
            
            
            
            foreach (var oldProduct in oldDb.STOCKs.OrderBy(x=>x.CODE))
            {
                count = 0;
                if (!string.IsNullOrEmpty(oldProduct.CODE))
                {
                    bool isTaxed = false;
                    if (oldProduct.TAX==true)
                    {
                        isTaxed = true;
                    }
                    Product product = new Product
                    {
                        Barcode = oldProduct.CODE,
                        Name = oldProduct.DESC,
                        ProductGroupId = db.ProductGroups.FirstOrDefault(x => x.Code == oldProduct.GROUP).Id,
                        Unit = oldProduct.UNIT,
                        IsTaxed = isTaxed
                    };
                    product.Prices.Add(new Price
                    {
                        StartDate = DateTime.Now,
                        Amount = Convert.ToDecimal(oldProduct.PRICE),
                        IsNormal = true
                    });
                    if (String.IsNullOrEmpty(product.Unit))
                        product.Unit = "";
                    db.Products.InsertOnSubmit(product);
                    db.SubmitChanges();
                    this.Text = "Completed : " + count.ToString();
                    count++;

                }
            }
             
            count = 0;
            foreach(var member in oldDb.MEMBERs.OrderBy
                (x=>x.CODE))
            {
                string gender="";
                if (!String.IsNullOrEmpty(member.SEX))
                    gender = member.SEX;
                db.Customers.InsertOnSubmit(new Customer
                {
                    Name = member.NAME + " " + member.SURNAME,
                    Address = member.ADD1 + " " + member.ADD2,
                    Code = member.CODE,
                    Gender = gender
                });
                db.SubmitChanges();
                this.Text = count++.ToString();
            }
            
                Bill bill;
                if (db.Bills.Count() > 0)
                {
                    bill = db.Bills.FirstOrDefault();
                }
                else
                {
                    bill = new Bill{
                        Date = DateTime.Now.Date,
                        IsCredit = false,
                        Note = "ยอดคงเหลือยกมา (1 เม.ย. 2553 - 31 มี.ค. 2554)",
                        SupplierId = null};
                }
            foreach (var item in oldDb.STOCKs.Where(x=>x.QTY.HasValue).Where(x=>x.QTY.Value>0))
            {
                bill.BillItems.Add(new BillItem{
                    Stock = new Stock{
                        Date = DateTime.Now.Date,
                        BuyingCost = Convert.ToDecimal(item.COST.Value * item.QTY.Value),
                        CurrentQuantity = Convert.ToDouble(item.QTY.Value),
                        OriginalQuantity = Convert.ToDouble(item.QTY.Value),
                        ProductId = productRepository.Get(item.CODE.Trim()).Id},
                });
            }
            if (db.Bills.Count() <= 0)
            {
                db.Bills.InsertOnSubmit(bill);
            }
            db.SubmitChanges();

            db.Employees.InsertOnSubmit(new Employee
            {
                Address = "-",
                Name = "สมหมาย",
                NationalId = "-",
                UserName = "sommai",
                PassWord = "1234",
                Telephone = "-"
            });
            db.SubmitChanges();

            db.PaymentTypes.InsertOnSubmit(new PaymentType
            {
                Name = "เงินสด",
                IsCredit = false,
                IsCaptitalPrice = false
            });
            db.SubmitChanges();

            db.PaymentTypes.InsertOnSubmit(new PaymentType
            {
                Name = "เครดิตสมาชิก",
                IsCredit = true,
                IsCaptitalPrice = false
            });
            db.SubmitChanges();

            db.PaymentTypes.InsertOnSubmit(new PaymentType
            {
                Name = "เดินสะพัดสำนักงานใหญ่",
                IsCredit = true,
                IsCaptitalPrice = true
            });
            db.SubmitChanges();
            */
            
    
    }


        private void pOSNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            POSForm posForm = new POSForm(employeeRepository.GetEmployee(1));
            posForm.Show();
        }


        private void adjustPriceNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            EditProductUserControl control = new EditProductUserControl();
            mainGroupControl.Controls.Add(control);
            control.searchTextEdit.Focus();

        }

        private void customerDetailsNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            EditCustomerUserControl control = new EditCustomerUserControl();
            mainGroupControl.Controls.Add(control);
            control.searchTextEdit.Focus();
        }

        private void addBillNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            AddBillUserControl control = new AddBillUserControl();
            mainGroupControl.Controls.Add(control);
        }

        private void invoiceDetailsNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            InvoiceDetailsUserControl control = new InvoiceDetailsUserControl();
            mainGroupControl.Controls.Add(control);
        }

        private void sellingReportNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            SellingReportsUserControl control = new SellingReportsUserControl();
            mainGroupControl.Controls.Add(control);
        }

        private void customerLoanNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
           
            AllCustomerLoanReport report = new AllCustomerLoanReport();
            List<Customer> customers = customerRepository.AllCustomers().Where(x => x.LoanAmount > 0).ToList();
            List<Customer> loanCustomers = new List<Customer>();
            int count = customers.Count();
            foreach (var cust in customers)
            {
                this.Text = "BISPOS :: สหกรณ์การเกษตรลับแล - ตรวจสอบข้อมูล: " + cust.Name;
                if (cust.LoanAmount != 0)
                    loanCustomers.Add(cust);
            }
            report.DataSource = loanCustomers;
            report.ShowPreview();
        }

        private void customerBuyReportNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            AllCustomerBuyReport report = new AllCustomerBuyReport();
            report.DataSource = customerRepository.AllCustomers().Where(x => (x.AllCreditBuyingCost + x.AllCashBuyingCost) > 0).ToList();
            report.ShowPreview();
        }

        private void productDetailsNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {

            mainGroupControl.Controls.Clear();
            EditProductUserControl control = new EditProductUserControl();
            mainGroupControl.Controls.Add(control);
            control.searchTextEdit.Focus();
        }

        private void productsReportNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            List<Product> products = productRepository.AllProducts().Where(x => x.StockCount > 0).ToList();
            List<ProductGroup> productGroups = productRepository.AllProductGroups().ToList();
            List<RProductGroup> rgroups = new List<RProductGroup>();
            foreach(ProductGroup group in productGroups.Where(x=>x.Products.Any(y=>y.StockCount>0)).OrderBy(x=>x.Code))
            {
                RProductGroup g = new RProductGroup
                {
                    Code = group.Code,
                    Name = group.Name
                };
                List<RProduct> rProducts = new List<RProduct>();
                foreach (var p in group.Products.Where(x=>x.Stocks.Count() > 0).Where(x => x.StockCount > 0).OrderBy(x => x.Name))
                {

                    rProducts.Add(new RProduct
                    {
                        Barcode = p.Barcode,
                        Name = p.Name,
                        Quantity = p.StockCount,
                        UnitCost = p.CapitalCost,
                        UnitPrice = p.CurrentPrice.Amount
                    });
                }
                g.Products = rProducts;
                rgroups.Add(g);
               
            }
            BISPOS.Report.DailyReport report = new DailyReport();
            report.DataSource = rgroups;
            report.fromDate.Value = DateTime.Now.Date.ToShortDateString();
            report.toDate.Value = "";
            report.RequestParameters = false;
            report.ShowPreview();
        }

        private void buyingReportNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            BuyingReport report = new BuyingReport();
            report.DataSource = billRepository.AllBills().OrderBy(x => x.Date).ToList();
            report.ShowPreview();
        }

        private void addCustomerNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            AddCustomerUserControl control = new AddCustomerUserControl(this);
            mainGroupControl.Controls.Add(control);
        }

        private void AddNewStockFromLastYear_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            AddNewYearStockXtraForm form = new AddNewYearStockXtraForm();
            form.Show();
        }

        private void devideProductNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            DevideProductXtraForm form = new DevideProductXtraForm();
            form.Show();
        }

        private void addProductnNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            AddNewProductXtraForm form = new AddNewProductXtraForm();
            form.Show();
        }

        private void dailySlipReportNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            mainGroupControl.Controls.Clear();
            DailySlipReportUserControl control = new DailySlipReportUserControl();
            mainGroupControl.Controls.Add(control);
        }

        private void addSupplierNavBarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            AddSupplierForm form = new AddSupplierForm();
            form.Show();
        }
    }
}
